import javax.sql.DataSource;
import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.time.chrono.IsoEra;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    public UdpEchoClient(String ip,int port) throws SocketException {
        serverIp = ip;
        serverPort = port;

        socket = new DatagramSocket();
    }


    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("客户端启动");

        while(true) {
            System.out.println("->");
            // scanner.next() 会以空格为分隔符
//            String request = scanner.next();
            String request = scanner.nextLine();
            // 构造请求对象
            DatagramPacket requestPacket = new DatagramPacket(
                    request.getBytes(),          // The data to be sent (converted to bytes)
                    request.getBytes().length,   // The length of the data
                    InetAddress.getByName(serverIp), // The IP address of the server
                    serverPort                   // The port number of the server
            );

            socket.send(requestPacket);
            // 读取服务器的响应
            byte[] buffer = new byte[1024];
            DatagramPacket responsePacket = new DatagramPacket(buffer,buffer.length);
            socket.receive(responsePacket);
            String resposne = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(resposne);
            }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }

}
